const Koa = require('koa')
const views = require('koa-views')
const bodyParser = require('koa-bodyparser');
const router = require('koa-router')()
const koaStatic = require('koa-static')
const path = require('path')
const cartModel = require('./vuex_shopping_cart/api/mysql')

const app = new Koa()

app.use(koaStatic(
    path.join(__dirname, '../../dist')
))

app.use(views(__dirname + '../../dist'))

app.use(bodyParser({
    formLimit: '1mb'
}))

router.get('/', async ctx => {
    await ctx.render('index')
})

router.post('/products', async ctx => {
    await cartModel.findAllProducts()
        .then(result => {
            ctx.body = result
        }).catch(err => {
            console.log(err)
        })
})

router.post('/updateProducts', async ctx => {
    let message = ''
    for (let product of ctx.request.body.products) {
        cartModel.findProductById(product.id)
            .then(result => {
                var values = []
                values.push(result[0].inventory - product.quantity)
                values.push(product.id)
                return cartModel.updateProducts(values)
            }).then(result => {
                message = 'success'
            }).catch(err => {
                console.log(err)
            })
    }
    ctx.body = message
})

app.use(router.routes())

app.listen(3001);

console.log(`listening on port 3001`)